package com.ruizhong.centercontroll.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruizhong.centercontroll.dao.TUserMapper;
import com.ruizhong.centercontroll.entity.TPermission;
import com.ruizhong.centercontroll.entity.TUser;
import com.ruizhong.centercontroll.entity.TUserPermission;
import com.ruizhong.centercontroll.service.TUserPermissionService;
import com.ruizhong.centercontroll.service.TUserService;
import com.ruizhong.centercontroll.util.MD5Hash;
import com.ruizhong.centercontroll.util.SaltedMD5Encryptor;
import com.ruizhong.centercontroll.util.StatusConstants;
import com.ruizhong.centercontroll.vo.PageSearchVO;
import com.ruizhong.centercontroll.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements TUserService {

    @Autowired
    private TUserPermissionService tUserPermissionService;

    @Override
    public PageVO<TUser> getUserPage(PageSearchVO pageSearchVO) {
        Integer pageNo = pageSearchVO.getPageNo();
        Integer pageSize = pageSearchVO.getPageSize();
        Page<TUser> page = new Page(pageNo, pageSize);
        Page<TUser> tUserPage = null;
        tUserPage = lambdaQuery().page(page);
        List<TUser> list = tUserPage.getRecords();
        PageVO<TUser> userPageVO = new PageVO<>(tUserPage.getTotal(), list);
        return userPageVO;
    }

    @Override
    public void submitAddUser(TUser tUser) {
        tUser.setUserStatus(StatusConstants.enabled);
        tUser.setPassword(SaltedMD5Encryptor.getSaltedMD5Hash(tUser.getUsername(), tUser.getPassword()));
        save(tUser);
    }

    @Override
    public List<TPermission> getPermissionDetailByUserIds(ArrayList<String> userIds) {
        List<TUser> usersDetail = tUserPermissionService.getPermissionIdsByUserIds(userIds);
        HashMap<String, List<Integer>> userIdMapPermissionList = new HashMap<>();

        return null;
    }



    public static Map<String, TUser> tokenMapUser = new HashMap<>();
    public static Map<String, String> userIdMapToken =new HashMap<>();

    @Override
    public String login(Map<String, Object> conditionMap) {
        if (conditionMap.get("userName") == null  || conditionMap.get("password") == null) {
            throw new RuntimeException("请完整填写信息");
        }
        String userName = conditionMap.get("userName").toString().trim();
        String password = conditionMap.get("password").toString().trim();
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            throw new RuntimeException("请完整填写信息");
        }
        String secretPassword = MD5Hash.md5Hash(password, userName, 3);
        TUser recordUser = lambdaQuery()
                .eq(TUser::getUsername, userName)
                .one();
        if (recordUser == null){
            throw new RuntimeException("该用户不存在");
        }
        if (!secretPassword.equals(recordUser.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        String token = UUID.randomUUID().toString();
        String existToken = userIdMapToken.get(recordUser.getId());
        if (!StringUtils.isEmpty(existToken)) {
            tokenMapUser.remove(existToken);
        }
        tokenMapUser.put(token, recordUser);
        userIdMapToken.put(recordUser.getId(), token);
        return token;
    }

    @Override
    @Transactional
    public void addNewUser(Map<String, String> conditionMap) {
        if (conditionMap.get("username") == null || conditionMap.get("password") == null){
            throw new RuntimeException("请完整填写信息");
        }
//        检验用户名是否已经重复
        String username = conditionMap.get("username").trim();
        String password = conditionMap.get("password").trim();
        TUser tUser = lambdaQuery()
                .eq(TUser::getUsername, username)
                .one();
        if (tUser!=null){
            throw new RuntimeException("该用户已存在");
        }
        tUser = new TUser();
        tUser.setUsername(username);
        tUser.setPassword(MD5Hash.md5Hash(password,username,3));
        tUser.setUserStatus(1);
        save(tUser);
        TUserPermission tUserPermission = new TUserPermission();
        tUserPermission.setUserId(tUser.getId());
        tUserPermission.setSubmitNewSystem(0);
        tUserPermission.setGetAllSystems(0);
        tUserPermission.setGetSystemById(0);
        tUserPermission.setUpdateSystemById(0);
        tUserPermission.setDeleteSystemById(0);
        tUserPermission.setSearchSystemsByName(0);
        tUserPermission.setChangeLanguage(0);
        tUserPermission.setChangeMinimizeOnStartup(0);
        tUserPermission.setSaveNewPage(0);
        tUserPermission.setGetPageInfoByPageName(0);
        tUserPermission.setUpdatePage(0);
        tUserPermission.setGetAllPages(0);
        tUserPermission.setDelPageByPageId(0);
        tUserPermission.setSaveNewScheduledTask(0);
        tUserPermission.setGetAllScheduledTask(0);
        tUserPermission.setUpdateScheduledTaskById(0);
        tUserPermission.setDelTaskById(0);
        tUserPermission.setGetUserPage(0);
        tUserPermission.setSubmitAddUser(0);
        tUserPermission.setGetPermissionDetailByUserId(0);
        tUserPermissionService.save(tUserPermission);
    }

    @Override
    public void deleteUser(String username) {
        QueryWrapper<TUser> removeWrapper = new QueryWrapper<>();
        removeWrapper.lambda().eq(TUser::getUsername,username);
        remove(removeWrapper);
    }

    @Override
    public TUser getDatailByUserId(String id) {
        TUser tUser = getById(id);
        tUser.setPassword(null);
        return tUser;
    }

    @Override
    public void submitUpdate(Map<String, Object> conditionMap) {
        if (conditionMap.get("username") == null) {
            throw new RuntimeException("用户名不可为空");
        }
        String username = conditionMap.get("username").toString();
        String id = conditionMap.get("id").toString();
        List<TUser> tUsers = lambdaQuery()
                .eq(TUser::getUsername, username)
                .ne(TUser::getId, id)
                .list();
        if (!CollectionUtils.isEmpty(tUsers)){
            throw new RuntimeException("用户名重复");
        }
        Object password = conditionMap.get("password");
        lambdaUpdate()
                .set(TUser::getUsername,username)
                .set(password != null,TUser::getPassword,MD5Hash.md5Hash(password.toString(),username,3))
                .update();
    }

    @Override
    public TUserPermission getPermissionsByUserId(String userId) {
        TUserPermission tUserPermission = tUserPermissionService.lambdaQuery()
                .eq(TUserPermission::getUserId, userId)
                .one();
        return tUserPermission;
    }

    @Override
    public void updatePermissionsByUserId(TUserPermission tUserPermission) {
        tUserPermissionService.updateById(tUserPermission);
    }
}
